/**
 * 总弹窗状态变化及联系人按钮人数显示
 * by blue
 */
fangimjs.define('view/totalWindowView', ['jquery', 'event/event', 'setting/setting', 'util/drag/1.0.0/drag'], function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        event = require('event/event'),
        vars = fangimjs.data.vars,
        setting = require('setting/setting').getInstance();

    var drag = require('util/drag/1.0.0/drag');

    var firstShow = true;

    function totalWindowView() {
        this.chatW = '#chatW'; //窗口主体id
        this.chatWR = '#chatW_rt'; //窗口右侧联系人列表id
        this.chatWL = '#chatW_l'; //窗口左侧聊天窗口id
        this.chatWLC = '#chatW_l_close'; //关闭窗口id
        this.chatWRM = '#chatW_rt_min'; //缩小窗口id
        this.chatWRC = '#chatW_rt_close'; //关闭窗口id
        this.newAlert = '#chatW_newAlert'; //新消息id
        this.newAlertNum = '#chatW_min_num'; //新消息数量id

        this.btnServiceClass = 'btnService'; //窗口展开
        this.btnServiceUpClass = 'btnServiceUp'; //窗口缩小类名
        this.btnOnlineTalkClass = 'btnOnlineTalk'; //联系人展开类名
        this.btnOnlineTalkUpClass = 'btnOnlineTalkUp'; //联系人缩小类名

        this.alertConId = '#alertCon'; //系统消息显示容器id

        this.FLASH_TIME = 1000; //新消息闪动间隔
        this.flashAlertFunc = 0; //setInterval函数执行新消息闪动效果标识
        this.showText = '【新消息*条】'; //title需要显示的内容\u3010\u65b0\u6d88\u606f*\u6761\u3011,*用来表示条数
        this.winStatus = ''; //窗口状态预存
        this.orginTitle = ''; //原始title内容预存
        this.loginSetTimeOutFlag = 0; //自动登录的settimerout标记预存
    };
    totalWindowView.prototype = {
        /**
         * 初始化函数
         * 声明联系人按钮操作窗口显示隐藏
         * 声明关闭按钮隐藏左侧聊天窗口
         * 声明缩小按钮隐藏窗口
         */
        init: function () {
            var that = this;
            that.doc = $(document);
            // 缩小窗口
            that.chatWRClose = $(that.chatWRC);
            that.orginTitle = that.doc.attr('title');
            that.chatBox = vars.chatBox;
            that.chatBoxMain = vars.chatBoxMain;
            that.chatBoxDetail = vars.chatBoxDetail;
            that.chatBoxNewMsg = vars.chatBoxNewMsg;
            that.chatBoxPhone = vars.chatBoxPhone;
            that.onlineTimeCon = vars.onlineTimeCon;
            that.btnServiceUp = vars.btnServiceUp;
            that.btnOnlineTalkUp = vars.btnOnlineTalkUp;

            if (vars.config.type === setting.type.sfb) {
                that.btnServiceUp.html('搜房帮在线咨询').css('font', 'bold 16px/35px SimSun');
                that.onlineTimeCon.html('客服在线时间：(不在线可留言)<br>周一到周五 早9:00~晚5:30');
            }

            // 不显示关闭按钮
            if (!vars.config.closeBtnShow) {
                that.chatWRClose.hide();
            }
            that.btnServiceUp.on('click', function () {
                var boxState = '';
                if (that.btnServiceUp.hasClass(that.btnServiceClass)) {
                    boxState = setting.WINDOW_STATUS_TINY;
                } else {
                    boxState = setting.WINDOW_STATUS_MAIN;
                }
                event.trigger('view:window:change', boxState);
            });
            that.btnOnlineTalkUp.on('click', function () {
                event.trigger('view:window:change', setting.WINDOW_STATUS_MAIN);
            });
            $(that.chatWLC).on('click', function () {
                event.trigger('view:window:change', setting.WINDOW_STATUS_MAIN);
            });
            $(that.chatWRM).on("click", function () {
                event.trigger('view:window:change', setting.WINDOW_STATUS_TINY);
            });
            that.chatBoxNewMsg.on('click', function () {
                event.trigger('view:newmsg:click');
            });
            var hasEnter = false;
            that.doc.on('mouseenter mouseover.fangChat', function (e) {
                if (!hasEnter) {
                    // console.log(new Date().getTime(), e.type);
                    event.trigger('view:mouse:enter', true);
                }
                hasEnter = true;
                that.doc.off('mouseover.fangChat');
            });
            that.doc.on('mouseleave', function (e) {
                event.trigger('view:mouse:enter', false);
                hasEnter = false;
                // console.log(new Date().getTime(), e.type);
            });

            // 拖拽支持
            that.dragBar = that.chatBoxDetail.find('#chatW_L_DX');
            that.dragBar.on(drag.types.start, function (event) {
                drag.create(that.chatBoxDetail, event, {
                    onEnd: adsorptEdge
                });
            });

            function adsorptEdge(drag) {
                var winHeight = $(window).height(),
                    winWidth = $(window).width(),
                    offset = that.chatBox.offset();
                var right = winWidth - drag.left - drag.width,
                    bottom = winHeight - drag.top - drag.height;
                that.chatBoxDetail.removeClass('notmove');
                // 新需求：扩大吸附范围为 30，不能超过联系列表。
                if (right < 210 && bottom < 30) {
                    // console.log('吸附还原');
                    that.chatBoxDetail.addClass('notmove').css({
                        left: '',
                        top: '',
                        right: '',
                        bottom: ''
                    });
                } else if (right < 210) {
                    // console.log('吸附联系人左侧');
                    that.chatBoxDetail.css({
                        left: '',
                        top: drag.top,
                        right: '',
                        bottom: ''
                    });
                } else if (bottom < 30) {
                    // console.log('吸附下边');
                    that.chatBoxDetail.css({
                        left: drag.left,
                        top: '',
                        right: '',
                        bottom: '-2px'
                    });
                } else {
                    that.chatBoxDetail.css({
                        left: drag.left,
                        top: drag.top,
                        right: '',
                        bottom: ''
                    });
                }
                /*
                if( right < 210 && right > 170 && bottom < 30 ) {
                    // console.log('吸附联系人左侧');
                    that.chatBoxDetail.addClass('notmove').css({left: '', top: '', right: '', bottom: ''});
                } else if ( right < 10 && bottom < 10 ) {
                    // console.log('吸附右下角');
                    that.chatBoxDetail.css({left: '', top: '', right: 0, bottom: ''});
                } else if ( bottom < 10 ){
                    // console.log('吸附下边');
                    that.chatBoxDetail.css({left: drag.left, top: '', right: '', bottom: '-2px'});
                } else if ( right - offset.left > 170 ){
                    // console.log('吸附右侧');
                    that.chatBoxDetail.css({left: '', top: drag.top, right: 0, bottom: ''});
                } else {
                    that.chatBoxDetail.css({left: drag.left, top: drag.top, right: '', bottom: ''});
                }
                */
            }
        },

        /**
         * 根据窗口状态显示窗口
         * @param {Object} obj
         * all 显示窗口
         */
        updateWinShow: function (obj) {
            var that = this;
            // 两种情况不需要更新窗口状态
            // 1.状态一致
            // 2.隐藏状态下设置初始状态，取返
            if (that.winStatus === obj.boxState || !!vars.config.hidden && obj.boxState !== setting.WINDOW_STATUS_CLOSE) {
                return;
            }
            // @update yueyanlei 增加了关闭的状态
            if (that.winStatus === setting.WINDOW_STATUS_CLOSE) {
                that.chatBox.show();
            }
            that.winStatus = obj.boxState;

            switch (that.winStatus) {
                case setting.WINDOW_STATUS_MAX:
                    that.btnServiceUp.removeClass().addClass(that.btnServiceClass).hide();
                    that.btnOnlineTalkUp.removeClass().addClass(that.btnOnlineTalkClass).hide();
                    that.chatBoxMain.add(that.chatBoxDetail).show();
                    if (that.flashAlertFunc) {
                        that.chatBoxNewMsg.hide();
                    }
                    if (vars.config.type === setting.type.haiwai) {
                        that.chatBoxPhone.hide();
                    }
                    that.chatBox.css({
                        'height': '556px',
                        'width': '180px'
                    });
                    break;
                case setting.WINDOW_STATUS_MAIN:
                    that.btnServiceUp.removeClass().addClass(that.btnServiceClass).hide();
                    that.btnOnlineTalkUp.removeClass().addClass(that.btnOnlineTalkClass).hide();
                    that.chatBoxMain.show();
                    that.chatBoxDetail.hide();
                    that.chatBox.css({
                        'height': '556px',
                        'width': '180px'
                    });
                    that.chatBoxPhone.hide();
                    that.chatBoxNewMsg.hide();
                    break;
                case setting.WINDOW_STATUS_TINY:
                    if (vars.config.type === setting.type.haiwai || vars.config.type === setting.type.sfb) {
                        that.btnServiceUp.removeClass().addClass(that.btnServiceUpClass).show();
                        that.btnOnlineTalkUp.removeClass().addClass(that.btnOnlineTalkClass).hide();
                        that.chatBox.css('height', '35px');
                    } else {
                        that.btnServiceUp.removeClass().addClass(that.btnServiceClass).hide();
                        that.btnOnlineTalkUp.removeClass().addClass(that.btnOnlineTalkUpClass).show();
                        that.chatBox.css('height', '30px');
                    }
                    that.chatBoxMain.add(that.chatBoxDetail).hide();
                    that.chatBoxDetail.css({
                        left: '',
                        top: '',
                        right: '',
                        bottom: ''
                    });
                    if (that.flashAlertFunc) {
                        that.chatBoxNewMsg.show();
                    }
                    if (vars.config.type === setting.type.haiwai) {
                        that.chatBoxPhone.show();
                    }
                    break;
                case setting.WINDOW_STATUS_CHAT:
                    that.btnServiceUp.removeClass().addClass(that.btnServiceClass).hide();
                    that.btnOnlineTalkUp.removeClass().addClass(that.btnOnlineTalkClass).show();
                    that.chatBoxMain.hide();
                    that.chatBox.css('height', '30px');
                    that.chatBoxPhone.hide();
                    that.chatBoxNewMsg.hide();
                    break;
                case setting.WINDOW_STATUS_CLOSE:
                    that.chatBox.hide();
                    break;
                default:
                    console.log('totalWindowView.js updateWinShow error!');
                    break;
            }
            if (firstShow) {
                // if(vars.config.type === setting.type.haiwai || vars.config.type === setting.type.sfb){
                // that.sideMenCon.height(290);//这里需要注意这个290代表的是sideMen容器的高度，是因为添加了onlineTime容器所以要缩小它的高度
                // that.onlineTimeCon.show();
                // }
                // that.chatBoxBar.show();
                firstShow = false;
            }
        },
        /**
         * 改变联系人按钮显示联系人数量
         * @param {Object} ol 在线人数
         * @param {Object} all 总人数
         */
        changeContactNum: function (obj) {
            var that = this;
            if (undefined === that.jContactOnline) {
                that.jContactOnline = that.btnOnlineTalkUp.find('span:first')
            }
            if (undefined === that.jContactTotal) {
                that.jContactTotal = that.btnOnlineTalkUp.find('span:last')
            }
            that.jContactOnline.html(obj.online.toString());
            that.jContactTotal.html(obj.total.toString());
        },
        /**
         * 显示新消息
         * @param {Object} data 新消息数据
         */
        showNewAlert: function (data) {
            var that = this;
            var totalMsg = data.totalMsg;
            clearInterval(that.flashAlertFunc);
            that.flashAlertFunc = 0;
            that.doc.attr('title', that.orginTitle);
            if (totalMsg <= 0) {
                that.chatBoxNewMsg.hide();
                // yangfan remove 屏蔽定时显示联系电话窗口
                // if(vars.config.type === setting.type.haiwai){
                //     that.chatBoxPhone.show();
                // }
                return;
            }
            if (vars.config.type === setting.type.haiwai) {
                // that.chatBoxPhone.is(":visible")&&that.chatBoxPhone.hide();
                that.chatBoxPhone.hide();
            }
            // 有新的消息时，显示新消息对话框，初始时有回调进行回调。
            $(that.newAlertNum).html(totalMsg);
            if (that.winStatus === setting.WINDOW_STATUS_TINY) {
                that.chatBoxNewMsg.show();
            } else if (that.winStatus === setting.WINDOW_STATUS_CLOSE && vars.config.newMesg) {
                $.isFunction(vars.config.newMesg) && vars.config.newMesg();
            }
            // 进行窗口标题显示提示
            that.flashAlertFunc = setInterval(function () {
                if (that.doc.attr('title') === that.orginTitle) {
                    that.doc.attr('title', that.showText.replace('*', totalMsg));
                } else {
                    that.doc.attr('title', that.orginTitle);
                }
            }, that.FLASH_TIME);
        },
        /**
         * 显示系统消息
         * @param data 系统消息数据
         * {type:'',value:''}
         */
        showSystemInfo: function (data) {
            var that = this;
            var type = data.type;
            var value = data.value;
            var str = '';
            var timing = false;
            switch (type) {
                case 'login':
                    str = that.loginInfo(value);
                    if (value == 2) {
                        timing = true;
                    }
                    break;
                case 'sucess':
                    str = '连接服务器成功'; // \u8fde\u63a5\u670d\u52a1\u5668\u6210\u529f
                    timing = true;
                    break;
                case 'kick':
                    str = '该帐户已在其他客户端登录'; // \u8be5\u5e10\u6237\u5df2\u5728\u5176\u4ed6\u5ba2\u6237\u7aef\u767b\u5f55
                    break;
                case 'socket_close':
                    str = '服务器连接错误，已关闭'; //\u670d\u52a1\u5668\u8fde\u63a5\u9519\u8bef,\u5df2\u5173\u95ed
                    break;
                case 'socket_error':
                    value = 3000 || parseInt(value);
                    var delay = parseInt(value / 1000);
                    str = '服务器错误，将在' + delay + '秒后重新连接，<a href="javascript:;" class="im_reconnect">立即重连</a>';
                    break;
                case 'max_times':
                    str = '服务器错误，<a href="javascript:;" class="im_reconnect">立即重连</a>'; //\u670d\u52a1\u5668\u8fde\u63a5\u9519\u8bef，\u7acb\u5373\u91cd\u8fde
                    break;
                case 'flash_error':
                    str = '当前IM系统需要flash插件支持,<br/>请安装.';
                case 'hide':
                    break;
                case 'verify_failure':
                    str = '请您 <a href="https://passport.fang.com?backurl=' + window.location.href + '">重新登录</a>';
                    break;
                case 'sfut_null':
                    str = '请 <a href="https://passport.fang.com?backurl=' + window.location.href + '" >登录</a> 后咨询';
                    if (vars.config.type === setting.type.xf) {
                        $(this.alertConId).addClass('webxf');
                    }
                    break;
            }
            var alertCon = $(this.alertConId);
            var timer;
            if (str) {
                alertCon.html(str).show();
                if (alertCon.find('a.im_reconnect').length > 0) {
                    alertCon.find('a.im_reconnect').on('click', function () {
                        clearTimeout(timer);
                        // 发送重连事件
                        event.trigger('view:socket:login');
                    });
                }
                if (type === 'socket_error') {
                    timer = setTimeout(function () {
                        event.trigger('view:socket:login');
                    }, value);
                }
                if (timing) {
                    setTimeout(function () {
                        alertCon.hide();
                    }, 2000);
                }
                if (firstShow) {
                    that.updateWinShow({
                        'boxState': setting.WINDOW_STATUS_TINY
                    });
                }
            } else {
                if (alertCon.is(':visible')) {
                    alertCon.hide();
                }
            }
        },
        /**
         * 登陆消息显示
         * @param state
         * @returns {string}
         */
        loginInfo: function (state) {
            var result = '';
            switch (state) {
                case 1:
                    result = '正在等待服务器回应...'; //\u6b63\u5728\u7b49\u5f85\u670d\u52a1\u5668\u56de\u5e94
                    break;
                case 2:
                    result = '目前处于连接状态'; //\u76ee\u524d\u5904\u4e8e\u8fde\u63a5\u72b6\u6001'
                    break;
                case 3:
                    result = '服务器错误，请刷新链接，重新登陆。'; //\u83b7\u53d6\u670d\u52a1\u5668\u0049\u0050\u9519\u8bef，\u8bf7\u5237\u65b0\u7f51\u9875，\u91cd\u65b0\u8fde\u63a5。
                    break;
                default:
                    result = '正在连接服务器...'; //\u6b63\u5728\u8fde\u63a5\u670d\u52a1\u5668
            }
            return result;
        },
        /**
         * 打开对话框
         */
        open: function () {
            if (this.flashAlertFunc) {
                event.trigger('view:newmsg:click');
            } else {
                event.trigger('view:window:change', setting.WINDOW_STATUS_MAIN);
            }
        }

    };
    module.exports = new totalWindowView;
});